import React, { Component } from 'react'
import {
  HashRouter as Router,
  Switch,
  Route,
  Link
} from 'react-router-dom'

const Sun = ()=> {
  return <h2>Sun</h2>
}

const Moon = ({ routes })=> {
  return (
    <div>
      <h2>Moon</h2>
      <ul>
        <li><Link to='/moon/star1'>StarOne</Link></li>
        <li><Link to='/moon/star2'>StarTwo</Link></li>
      </ul>
      <Switch>
        {
          routes.map((route, i)=>{
            return (
              <RouteWithSubRoutes key={i} {...route}></RouteWithSubRoutes>
            )
          })
        }
      </Switch>
    </div>
  )
}

const StarOne = ()=> {
  return <h3>StarOne</h3>
}

const StarTwo = ()=> {
  return <h3>StarTwo</h3>
}

//配置路由项目
const routes = [
  {
    path: '/sun',
    component: Sun
  },
  {
    path: '/moon',
    component: Moon,
    routes: [
      {
        path: '/moon/star1',
        component: StarOne
      },
      {
        path: '/moon/star2',
        component: StarTwo
      }
    ]
  }
]

function RouteWithSubRoutes(route) {
  return (
    <Route
      path={route.path}
      render={props=>(
        <route.component {...props} routes={route.routes}></route.component>
      )}></Route>
  )
}

export default class App extends Component {
  render() {
    return (
      <div>
        <Router>
          <ul>
            <li><Link to='/sun'>Sun</Link></li>
            <li><Link to='/moon'>Moon</Link></li>
          </ul>
          <Switch>
            {routes.map((route, i)=>(
              <RouteWithSubRoutes key={i} {...route}/>
            ))}
          </Switch>
        </Router>
      </div>
    )
  }
}
